<?php
namespace PsiFramework\Classes\Util\Object;

import("Classes.Util.Object.File");
import("Classes.Model.ModelInterface.IPrimitiveObject");
import("Classes.Util.Database.Query.SqlType");

use \PsiFramework\Classes\Util\Database\Query\SqlType;
use \PsiFramework\Classes\Model\ModelInterface\IPrimitiveObject;
use \PsiFramework\Classes\Util\Object\Image;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The ImageCollection class represents an array of images
 *
 * @package Util.Object
 */
class ImageCollection implements IPrimitiveObject
{

    protected /*Image[]*/   $_images ;

    /**
     * Constructor
     *
     * @param  Image[] $images the file which contains the image
     * 
     * @return ImageCollection 
     */
    public function __construct(/*Image[]*/ $images=array())
    {
        $this->_images = $images ;
    }

    public function size()
    {
        return count($this->_images);
    }
    
    public function addImage(Image $image)
    {
    	$this->_images[] = $image;
    }
    
    public function getImages()
    {
    	return $this->_images;
    }
    
    public function getImage(/*int*/ $i)
    {
    	if ($this->size()-1 >= $i) {
            return $this->_images[$i];
    	} else {
    	    return null;
    	}
    }
    
    public function first()
    {
        return $this->getImage(0);
    }
    
    public function rand()
    {
        $index = rand(0, $this->size());
        return $this->getImage($index);
    }

    public function containsImage(Image $image)
    {
        $contains = false;
        foreach ($this->_images as $img) {
            if ($image->getFileLink() == $img->getFileLink()) {
                $contains = true;
                break;
            }
        }
        return $contains;
    }
    
    public function serialize(/*boolean*/ $asText=true)
    {
        $serialized = array();
        
        foreach ($this->_images as $image) {
            $serialized[] = $image->serialize(false);
        }
        
        if ($asText) {
        	return json_encode($serialized);
        } else {
        	return $serialized ;
        }
    }

    public function unserialize(/*string*/ $text)
    {
        $this->_images = array();
        $json = json_decode($text);
        foreach ($json as $jsonElement) {
            $image = new Image();
            $image->unserialize($jsonElement);
            $this->_images[] = $image;
        }
    }

    public function toString()
    {
        return $this->serialize();
    }
    
    public function __toString()
    {
        return $this->toString();
    }

    public static function getSqlType()
    {
        return SqlType::$text ;
    }
}
